import React, { useEffect, useRef, useState, useCallback } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';
import img1 from '../../../assets/img/3.png'
import './Mapcontainer.less';

// 声明全局 AMap 类型
declare global {
  interface Window {
    AMap: any;
  }
}

interface MapData {
  value: number;
  name: string;
}

interface MapContainerProps {
  mapData: MapData[];
  title: string;
  subtitle: string;
}

interface SatelliteMapProps {
  center?: [number, number];
  zoom?: number;
}

const SatelliteMap:React.FC<SatelliteMapProps> = ({
  center = [118.353483, 29.397287],
  zoom = 18, // 默认缩放级别
}) => {
  const mapRef = useRef<HTMLDivElement>(null);
  const mapInstance = useRef<any>(null);
  const satelliteLayer = useRef<any>(null);
  const defaultLayer = useRef<any>(null);
  const [isSatellite, setIsSatellite] = useState(true);
  const markerPath = useRef<[number, number][]>([
    [118.352571, 29.39692],
    [118.352715, 29.397047],
    [118.352775, 29.397201],
    [118.352823, 29.397355],
    [118.352975, 29.397541],
    [118.353023, 29.397627],
    [118.353171, 29.397621],
    [118.353306, 29.397533],
    [118.353499, 29.397428],
    [118.353606, 29.397388],
    [118.353783, 29.397322],
    [118.353939, 29.39722],
    [118.354083, 29.397126],
    [118.354207, 29.397065],
    [118.35425, 29.397009],
    [118.354196, 29.396944],
    [118.354137, 29.396841],
    [118.354079, 29.396794],
    [118.354013, 29.396652],
    [118.353955, 29.396541]
  ]);

  // 添加标注点
  const addMarkers = (AMap: any) => {
    // 水库标注
    const reservoirMarker = new AMap.Marker({
      position: [118.353434, 29.397181],
      title: '齐溪水库',
      icon: new AMap.Icon({
        size: new AMap.Size(30, 30),
        image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
        imageSize: new AMap.Size(30, 30),
      }),
      label: {
        content: '齐溪水库',
        direction: 'top',
        offset: new AMap.Pixel(0, -30),
        style: {
          background: '#fff',
          padding: '2px 5px',
          borderRadius: '2px',
          border: '1px solid #ccc'
        }
      }
    });

    // 房屋标注
    const buildings = [
      { position: [118.353783, 29.397322], title: '管理用房' },
      { position: [118.353939, 29.39722], title: '泵站' },
      { position: [118.354083, 29.397126], title: '闸门' },
      { position: [118.354207, 29.397065], title: '观测站' }
    ];

    buildings.forEach(building => {
      const marker = new AMap.Marker({
        position: building.position,
        title: building.title,
        icon: new AMap.Icon({
          size: new AMap.Size(25, 25),
          image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          imageSize: new AMap.Size(25, 25),
        }),
        label: {
          content: building.title,
          direction: 'top',
          offset: new AMap.Pixel(0, -25),
          style: {
            background: '#fff',
            padding: '2px 5px',
            borderRadius: '2px',
            border: '1px solid #ccc'
          }
        }
      });
      mapInstance.current.add(marker);
    });

    mapInstance.current.add(reservoirMarker);
  };

  // 切换图层函数
  const toggleLayer = useCallback(() => {
    if (!mapInstance.current) return;
    const nextMode = !isSatellite;
    if (nextMode) {
      mapInstance.current.setLayers([satelliteLayer.current]);
      // 切换到卫星图时添加标注
      addMarkers(window.AMap);
    } else {
      mapInstance.current.setLayers([defaultLayer.current]);
      // 切换到普通地图时清除标注
      mapInstance.current.clearMap();
      // 重新添加路线
      const polyline = new window.AMap.Polyline({
        path: markerPath.current,
        strokeColor: "#2080dc",
        strokeOpacity: 1,
        strokeWeight: 5,
        strokeStyle: "solid",
      });
      polyline.setMap(mapInstance.current);
    }
    setIsSatellite(nextMode);
  }, [isSatellite]);

  const onclick = (e: any) => {
    const lnglat = e.lnglat; // 获取点击位置的经纬度
    console.log('点击位置的经纬度:', lnglat);
  };

  useEffect(() => {
    AMapLoader.load({
      key: '8be2bfb5fa90730e0385e612261c8de5',
      version: '2.0',
      plugins: ['AMap.TileLayer.Satellite', 'AMap.TileLayer'],
    }).then((AMap) => {
      if (!mapRef.current) return;

      // 初始化图层
      satelliteLayer.current = new AMap.TileLayer.Satellite();
      defaultLayer.current = new AMap.TileLayer();

      // 创建地图实例
      mapInstance.current = new AMap.Map(mapRef.current, {
        zoom: 18,
        center: [118.353434, 29.397181],
        layers: [satelliteLayer.current],
      });

      mapInstance.current.on('click', onclick);
      
      // 添加路线
      const polyline = new AMap.Polyline({
        path: markerPath.current,
        strokeColor: "#2080dc",
        strokeOpacity: 1,
        strokeWeight: 5,
        strokeStyle: "solid",
      });
      polyline.setMap(mapInstance.current);

      // 添加初始标注
      addMarkers(AMap);

    }).catch(console.error);

    // 清理地图实例
    return () => {
      if (mapInstance.current) {
        mapInstance.current.destroy();
        mapInstance.current = null;
      }
    };
  }, [center, zoom]); // 依赖项中移除 isSatellite

  return (
    <div className="map-container">
      <div
        ref={mapRef}
        style={{ width: '100%', height: '100%', borderRadius: '8px' }}
      />
      <button
        onClick={toggleLayer}
        className="map-toggle-button"
      >
        {isSatellite ? '切换普通地图' : '切换卫星地图'}
      </button>
    </div>
  );
};

const getClientIP = async () => {
  try {
    const response = await fetch('/api/v1/services/opens/ips/format/json');
    const data = await response.json();
    return data.ip;
  } catch (error) {
    console.error('获取IP地址失败:', error);
    return null;
  }
};

export default SatelliteMap;